import { Routes, Route } from "react-router-dom";
import { lazy, Suspense, useEffect } from "react";
import { createContext, useState, useCallback } from "react";
import { Empty } from "@/components/Empty";
import { ErrorBoundary } from "react-error-boundary";
import { checkLogin } from "@/services/api";
import { useNavigate } from "react-router-dom";
import UserService from "@/services/user";
import { toast } from "sonner";
import ConfirmDialog from "@/components/ConfirmDialog";
import { getConfirmDialogState, closeConfirmDialog, confirmAction, addStateChangeListener } from "@/lib/dialog";
import { authEventManager } from "@/lib/auth-events";

const Home = lazy(() => import("@/pages/Home"));
const Login = lazy(() => import("@/pages/Login"));
const Register = lazy(() => import("@/pages/Register"));
const TeamList = lazy(() => import("@/pages/TeamList"));
const UserList = lazy(() => import("@/pages/UserList"));
const ProjectList = lazy(() => import("@/pages/ProjectList"));
const ProjectDetail = lazy(() => import("@/pages/ProjectDetail"));
const ProjectShare = lazy(() => import("@/pages/ProjectShare"));
const DocShare = lazy(() => import("@/pages/DocShare"));
const Editor = lazy(() => import("@/pages/Editor"));

interface UserInfo {
  userId: string;
  userName: string;
  userIcon: string;
  account: string;
  teamList: {
    teamId: string;
    teamName: string;
    teamIcon: string;
    type: 'OWNER' | 'PARTICIPANT';
  }[];
  projectList: {
    projectId: string;
    projectName: string;
    projectIcon: string;
    type: 'OWNER' | 'PARTICIPANT';
  }[];
}

export interface AuthContextType {
  isAuthenticated: boolean;
  userInfo: UserInfo | null;
  currentTeam: string | null;
  currentProject: string | null;
  currentProjectType?: string | null;
  currentProjectPermission?: string | null;
  setIsAuthenticated: (value: boolean) => void;
  setUserInfo: (user: UserInfo) => void;
  setCurrentTeam: (teamId: string) => void;
  setCurrentProject: (projectId: string) => void;
  logout: () => void;
  saveProjectContext: (projectId: string, teamId: string, type?: string, permission?: string) => void;
}

export const AuthContext = createContext<AuthContextType>({
  isAuthenticated: false,
  userInfo: null,
  currentTeam: null,
  currentProject: null,
  currentProjectType: null,
  currentProjectPermission: null,
  setIsAuthenticated: () => {},
  setUserInfo: () => {},
  setCurrentTeam: () => {},
  setCurrentProject: () => {},
  logout: () => {},
  saveProjectContext: () => {},
});

function ErrorFallback({error}: {error: Error}) {
  return (
    <div className="p-4 text-red-500">
      <h2>Something went wrong:</h2>
      <pre className="font-mono">{error.message}</pre>
    </div>
  );
}

export default function App() {
  const [isAuthenticated, setIsAuthenticated] = useState(() => {
    return !!localStorage.getItem('token');
  });
  const [userInfo, setUserInfo] = useState<UserInfo | null>(() => {
    const savedUserInfo = localStorage.getItem('userInfo');
    return savedUserInfo ? JSON.parse(savedUserInfo) : null;
  });
  const [currentTeam, setCurrentTeam] = useState<string | null>(() => {
    return localStorage.getItem('currentTeam');
  });
  const [currentProject, setCurrentProject] = useState<string | null>(() => {
    return localStorage.getItem('currentProject');
  });
  const [currentProjectType, setCurrentProjectType] = useState<string | null>(() => {
    return localStorage.getItem('currentProjectType');
  });
  const [currentProjectPermission, setCurrentProjectPermission] = useState<string | null>(() => {
    return localStorage.getItem('currentProjectPermission');
  });
  const [confirmDialogState, setConfirmDialogState] = useState(getConfirmDialogState());

  const saveProjectContext = useCallback((projectId: string, teamId: string, type?: string, permission?: string) => {
    setCurrentProject(projectId);
    setCurrentTeam(teamId);
    localStorage.setItem('currentProject', projectId);
    localStorage.setItem('currentTeam', teamId);
    if (type) {
      setCurrentProjectType(type);
      localStorage.setItem('currentProjectType', type);
    }
    if (permission) {
      setCurrentProjectPermission(permission);
      localStorage.setItem('currentProjectPermission', permission);
    }
  }, []);
  const navigate = useNavigate();

  // 监听认证失效事件
  useEffect(() => {
    const handleAuthFailure = () => {
      setIsAuthenticated(false);
      setUserInfo(null);
      setCurrentTeam(null);
      setCurrentProject(null);
      localStorage.removeItem("token");
      localStorage.removeItem("userInfo");
      localStorage.removeItem("currentTeam");
      localStorage.removeItem("currentProject");
      navigate('/login');
    };

    const removeListener = authEventManager.addListener(handleAuthFailure);
    return removeListener;
  }, [navigate]);

  // 检查登录状态并刷新页面数据
  useEffect(() => {
    const verifyLogin = async () => {
      try {
        console.log('开始检查登录状态...');
        const isLoggedIn = await checkLogin();
        console.log('登录状态检查结果:', isLoggedIn);
        setIsAuthenticated(isLoggedIn);
        
        const publicPaths = ['/', '/login', '/register', '/project-share', '/doc-share'];
        const currentPath = window.location.pathname;
        // 检查是否是分享页面路径
        const isSharePath = currentPath.startsWith('/project/') || currentPath.startsWith('/doc/');
        if (!isLoggedIn && !publicPaths.includes(currentPath) && !isSharePath) {
          navigate('/login');
        }
      } catch (error) {
        console.error('登录状态检查失败:', error);
        setIsAuthenticated(false);
        const publicPaths = ['/', '/login', '/register', '/project-share', '/doc-share'];
        const currentPath = window.location.pathname;
        // 检查是否是分享页面路径
        const isSharePath = currentPath.startsWith('/project/') || currentPath.startsWith('/doc/');
        if (!publicPaths.includes(currentPath) && !isSharePath) {
          navigate('/login');
        }
      }
    };

    // 立即执行认证检查，不添加额外延迟
    verifyLogin();
  }, [navigate]);

  // 监听确认对话框状态变化
  useEffect(() => {
    const checkConfirmDialog = () => {
      const state = getConfirmDialogState();
      console.log('App.tsx 收到状态变化通知，当前状态:', state); // 调试信息
      setConfirmDialogState(state);
    };

    const removeListener = addStateChangeListener(checkConfirmDialog);
    return removeListener;
  }, []);

  const logout = async () => {
    try {
      await UserService.logout();
      setIsAuthenticated(false);
      setUserInfo(null);
      setCurrentTeam(null);
      setCurrentProject(null);
      setCurrentTeam(null);
      setCurrentProject(null);
      localStorage.removeItem("token");
      localStorage.removeItem("userInfo");
      localStorage.removeItem("currentTeam");
      localStorage.removeItem("currentProject");
      navigate('/login');
    } catch (error: any) {
      console.error('退出登录失败:', error);
      toast.error(error.message || '退出登录失败');
    }
  };

  return (
    <ErrorBoundary FallbackComponent={ErrorFallback}>
      <div className="min-h-screen bg-gradient-to-br from-pink-100/70 via-blue-100/50 to-purple-100/60 dark:bg-black relative overflow-hidden">
        {/* 亮色模式背景 */}
        <div className="absolute inset-0 -z-10 dark:hidden">
          <svg 
            className="w-full h-full opacity-15"
            preserveAspectRatio="none" 
            viewBox="0 0 1200 800"
          >
            <path 
              d="M0,200 C150,100 450,300 600,200 C750,100 900,300 1200,200 L1200,800 L0,800 Z" 
              fill="url(#lightGradient)"
              opacity="0.9"
            ></path>
            <path 
              d="M0,400 C150,300 450,500 600,400 C750,300 900,500 1200,400 L1200,800 L0,800 Z" 
              fill="url(#lightGradient2)"
              opacity="0.6"
            ></path>
            
            <defs>
              <linearGradient id="lightGradient" x1="0%" y1="0%" x2="100%" y2="0%">
                <stop offset="0%" stopColor="#818cf8" />
                <stop offset="50%" stopColor="#c084fc" />
                <stop offset="100%" stopColor="#f472b6" />
              </linearGradient>
              <linearGradient id="lightGradient2" x1="0%" y1="0%" x2="100%" y2="0%">
                <stop offset="0%" stopColor="#a78bfa" />
                <stop offset="100%" stopColor="#34d399" />
              </linearGradient>
            </defs>
          </svg>
        </div>

      <AuthContext.Provider
        value={{ 
          isAuthenticated, 
          userInfo,
          currentTeam,
          currentProject,
          currentProjectType,
          currentProjectPermission,
          setIsAuthenticated, 
          setUserInfo,
          setCurrentTeam,
          setCurrentProject,
          logout,
          saveProjectContext
        }}
      >
          <Suspense fallback={<Empty />}>
            <Routes>
              <Route path="/" element={<Home />} />
              <Route path="/login" element={<Login />} />
              <Route path="/register" element={<Register />} />
              <Route path="/team-list" element={<TeamList />} />
              <Route path="/user-list" element={<UserList />} />
              <Route path="/project-detail" element={<ProjectDetail />} />
              <Route path="/project/:teamId/:id" element={<ProjectShare />} />
              <Route path="/doc/:id" element={<DocShare />} />
              <Route path="/editor" element={<Editor />} />
            </Routes>
          </Suspense>
        </AuthContext.Provider>

        {/* 全局确认对话框 */}
        <ConfirmDialog
          isOpen={confirmDialogState.isOpen}
          onClose={closeConfirmDialog}
          onConfirm={confirmAction}
          title={confirmDialogState.title}
          message={confirmDialogState.message}
          type={confirmDialogState.type}
          confirmText={confirmDialogState.confirmText}
          cancelText={confirmDialogState.cancelText}
        />
      </div>
    </ErrorBoundary>
  );
}
